package cn.com.bluemoon.daps.standard.client;

import cn.com.bluemoon.daps.api.model.RemoteDataModelService;
import cn.com.bluemoon.daps.api.model.RemoteDataModelTableService;
import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.exception.DapThrowException;
import cn.com.bluemoon.daps.model.entity.DapDataModel;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author Jarod.Kong
 */
@Service
@Slf4j
public class DapModelModuleFacade {
    @Autowired
    private RemoteDataModelService modelService;
    @Autowired
    private RemoteDataModelTableService tableService;

    public List<ModelInfo> queryAllDataWarehouseModelInfos() {
        // 获取所有模型
        try {
            ResultBean<List<DapDataModel>> res = modelService.findAllOrFindLikeName("");
            List<DapDataModel> data = res.getContent() == null ? Collections.emptyList() : res.getContent();
            return data.stream().filter(d -> 2 == d.getSysType()).map(m -> new ModelInfo(m.getId(), m.getName())).collect(Collectors.toList());
        } catch (Exception e) {
            throw new DapThrowException("获取模型名称失败", e);
        }
    }

    /**
     * 获取数仓模型
     */
    public Optional<ModelInfo> queryOneDataWarehouseModelInfo(String modelName) {
        return queryAllDataWarehouseModelInfos().stream().filter(m -> m.getModelName().equalsIgnoreCase(modelName)).findFirst();
    }

    /**
     * 表字段id
     */
    public Optional<Tuple2<String, String>> queryTableAndField(String modelId, String tableName, String fieldName) {
        try {
            ResultBean<List<String>> tableInfo = tableService.findTableInfo(modelId, tableName, fieldName);
            List<String> ids = tableInfo.getContent();
            if (ids != null && ids.size() == 2) {
                return Optional.of(Tuples.of(ids.get(0), ids.get(1)));
            }
        } catch (Exception e) {
            log.error("获取模型表和字段id失败", e);
        }
        log.info("modelId={}, tableName={}, fieldName={}，获取模型表和字段id为空", modelId, tableName, fieldName);
        return Optional.empty();
    }

    @RequiredArgsConstructor
    @Data
    public static class ModelInfo {
        private final String modelId;
        private final String modelName;

    }

}
